package com.erlinyou.im.web.controller.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.erlinyou.im.common.uuid.UUIDGenerator;
import com.erlinyou.im.model.offline.OfflineMessage;
import com.erlinyou.im.service.offline.IOfflineMessageService;
import com.erlinyou.im.web.vo.PushMessage;
import com.erlinyou.im.web.vo.PushMessage.PushMessageType;
import com.erlinyou.im.web.vo.SysMessageVo;
import com.erlinyou.im.web.wshandler.WSSManager;

public class SysMessageUtil {
	private static Logger logger = LoggerFactory.getLogger(SysMessageUtil.class);
	public static <T> boolean pushSysMessage(Long userid,T t,IOfflineMessageService offlineMessageService){
		try {
			SysMessageVo<T> sysMessageVo = new SysMessageVo<T>(UUIDGenerator.nextId(), System.currentTimeMillis(), t);
			String pushContent = new PushMessage<>(sysMessageVo, PushMessageType.SYS).buildJson();
			boolean isSaveSucc = true;
			if(offlineMessageService != null){
				OfflineMessage offlineMessage = new OfflineMessage();
				offlineMessage.setContent(pushContent);
				offlineMessage.setCt(sysMessageVo.getCreateTime());
				offlineMessage.setMsgid(sysMessageVo.getId());
				offlineMessage.setUserid(userid);
				isSaveSucc = offlineMessageService.save(offlineMessage) != null;
			}
			if(isSaveSucc){
				WSSManager.sendMessageText(userid, pushContent);
				return true;
			}
		} catch (Exception e) {
			logger.error("pushSysMessage error:",e);
		}
		return false;
	}
}
